<!--
* @description 上传文件
* @fileName upload_file.vue
* @author huangyu
* @date 2021/09/28 11:15:27
!-->
<template>
    <el-upload
    class="upload-demo"
    action="customize"
    :show-file-list="false"
    :http-request="uploadMoreImg">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
</template>

<script>
import cloudbase from "@cloudbase/js-sdk";
export default {
    components: {},
    data() {
        return {

        }
    },
    mounted() {
        
    },
    methods: {
        uploadMoreImg(params){
            // window.console.log(params)
            const isJPG = params.file.type === 'image/jpeg' || params.file.type === 'image/png';
            const isLt7M = params.file.size / 1024 / 1024 < 7;
            // window.console.log(isJPG,isLt7M)
            if(!isJPG){
                this.$message.error("只能上传 JPG 或 PNG 格式")
                return
            }
            if (!isLt7M) {
                this.$message.error('上传图片大小不能超过 7MB!');
                return
            }

            var year = new Date().getFullYear()
            var month = new Date().getMonth() + 1
            var day = new Date().getDate()
            var time = new Date().getTime().toString()
            if(day<10){
                day = "0"+day.toString()
            }
            var date = year.toString()+month.toString()+day.toString()
            let path = "WebServiceFiles/MyImage/"+year+"/"+date+"/"+time

            if(params.file.type === 'image/jpeg'){
                path = path+'.jpg'
            }
            if(params.file.type === 'image/png'){
                path = path+'.png'
            }

            // window.console.log(path)

            const app = cloudbase.init({
                env: "web-cloud0713-6g519i65f479e638"
            });

            app
            .uploadFile({
                cloudPath: path,
                filePath: params.file,
                // onUploadProgress: function (progressEvent) {
                //     window.console.log(progressEvent);
                //     var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                // }
            })
            .then((result) => {
                // 上传结果
                if(result){
                    this.$emit('tempFileURL',result.download_url)
                }
            }).catch(function (error) {
                alert(error)
            });
        },
    },
}
</script>

<style scoped>

</style>